﻿/**
 * 
 * Copyright 2009, 2010 Mike Jamer [email: mikejamer@gmail.com ]
 * 
 * This File is part of Moose IRC
 * 
 * MooseIRC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * MooseIRC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with MooseIRC.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

using moose.extension;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace moose.utility {

    /// <summary>
    /// Provides Driver/Extension discoverability Functionality
    /// </summary>
    internal static class DriverUtility {

        /// <summary>
        /// Cached Drivers
        /// </summary>
        private static Dictionary<string, Assembly> m_dictDrivers;

        /// <summary>
        /// Initializes Static Members
        /// </summary>
        static DriverUtility() {
            m_dictDrivers = new Dictionary<string, Assembly>();
            cache_drivers(); //caches all availale drivers in collection
        }

        /// <summary>
        /// Cache all available drivers
        /// </summary>
        private static void cache_drivers() {
            Assembly asm = null;
            object[] attributes;
            ExtensionAttribute attrib;
            foreach (string assembly_path in Directory.GetFiles(Environment.CurrentDirectory, "*.dll")) {
                try {
                    asm = Assembly.LoadFile(assembly_path);
                } catch (Exception) {
                    Console.Error.Write("Unable to load assembly: ");
                    Console.Write(assembly_path);
                    Console.WriteLine();
                }
                if (asm != null) {
                    attributes = asm.GetCustomAttributes(typeof(ExtensionAttribute), false);
                    if (attributes.Length == 1) { //we've found an extension
                        attrib = (ExtensionAttribute)attributes[0];
                        m_dictDrivers[attrib.Name] = asm;
                    }
                }
            }

            return;
        }

        /// <summary>
        /// Return Collection of all available drivers
        /// </summary>
        public static IEnumerable<Assembly> Extensions {
            get {
                return m_dictDrivers.Values;
            }
        }

    }

}
